package com.ysd.lis.service.qi.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.jdbc.JdbcConnectionManager;
import com.ysd.lis.entity.DataBaseBo;
import com.ysd.lis.entity.qi.QiDatabase;
import com.ysd.lis.enums.QiDataSourceEnum;
import com.ysd.lis.mapper.qi.QiDatabaseMapper;
import com.ysd.lis.request.qi.DatabaseDto;
import com.ysd.lis.request.qi.DatabaseParam;
import com.ysd.lis.service.qi.QiDatabaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 指标项目条件表 服务实现类
 * </p>
 *
 * @author PRS
 * @since 2024-07-01
 */
@Service
public class QiDatabaseServiceImpl extends ServiceImpl<QiDatabaseMapper, QiDatabase> implements QiDatabaseService {

    @Autowired
    QiDatabaseMapper qiDatabaseMapper;
    @Override
    public Result findQiDatabaseList(DatabaseParam param) {
        MPJLambdaWrapper<QiDatabase> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(QiDatabase.class)
                .eq(QiDatabase::getDelFlag,0);
        if (StringUtils.isNotBlank(param.getSeachValue())) {
            queryWrapper.and(wrapper -> wrapper.like(QiDatabase::getDatabaseCode, param.getSeachValue())
                    .or().like(QiDatabase::getDatabaseName,param.getSeachValue()));
        }
        queryWrapper.orderByAsc(QiDatabase::getSeq);
        List<QiDatabase> databaseList = qiDatabaseMapper.selectList(queryWrapper);

        return Result.succ(1, "查询成功", databaseList);

    }

    @Override
    public Result addDatabase(QiDatabase qiDatabase) {
        int insert = qiDatabaseMapper.insert(qiDatabase);
        if(insert>0){
            return Result.succ(1,"添加成功",qiDatabase);
        }else {
            return Result.fail(400,"添加失败","");
        }
    }

    @Override
    public Result editDatabase(QiDatabase qiDatabase) {
        int updateById = qiDatabaseMapper.updateById(qiDatabase);
        if(updateById>0){
            return Result.succ(1,"提交成功",qiDatabase);
        }else {
            return Result.fail(400,"修改失败","");
        }
    }

    @Override
    public Result batchDeleteDatabaseList(DatabaseDto dto) {
        List<QiDatabase> databaseList = dto.getDatabaseList();
        List<String> ids = databaseList.stream().map(QiDatabase::getId).distinct().collect(Collectors.toList());

        boolean b = this.removeByIds(ids);
        if(b){
            return Result.succ(1, "删除成功", null);
        }else {
            return Result.fail(400,"删除失败","");
        }
    }

    @Override
    public Result qiDatabaseConnection(QiDatabase qiDatabase) {
        Result result = Result.succ(1, "连接成功！", "ok");
        try {
            QiDataSourceEnum anEnum = QiDataSourceEnum.getEnum(qiDatabase);
            DataBaseBo dataBaseBo = anEnum.getFunc().apply(anEnum, qiDatabase);
            JdbcConnectionManager jdbcConnectionManager = new JdbcConnectionManager();
            Connection connection = jdbcConnectionManager.getConnection(dataBaseBo);
            if(connection == null){
                result = Result.fail("数据库连接失败，请查看连接信息或者数据服务状态！");
            }
            jdbcConnectionManager.closeConnection(connection);
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.fail("连接失败，请查看连接信息或者数据服务状态！");
        }
        return result;
    }
    @Override
    public Result qiDatabaseGetTables(String qiDatabaseId) {
        QiDatabase qiDatabase = qiDatabaseMapper.selectById(qiDatabaseId);
        List<String> list=new ArrayList<>();
        try {
            QiDataSourceEnum anEnum = QiDataSourceEnum.getEnum(qiDatabase);
            DataBaseBo dataBaseBo = anEnum.getFunc().apply(anEnum, qiDatabase);
            JdbcConnectionManager jdbcConnectionManager = new JdbcConnectionManager();
            Connection connection = jdbcConnectionManager.getConnection(dataBaseBo);
            if(connection == null){
               return Result.fail("数据库连接失败，请查看连接信息或者数据服务状态！");
            }
            DatabaseMetaData metaData = connection.getMetaData();

            // 获取所有表
            ResultSet tables = metaData.getTables(null, null, "%", new String[]{"TABLE"});
            while (tables.next()) {
                String tableName = tables.getString("TABLE_NAME");
                list.add(tableName);
            }
            jdbcConnectionManager.closeConnection(connection);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("数据库连接失败，请查看连接信息或者数据服务状态！");
        }
        return Result.succ(1, "连接成功！", list);
    }

    @Override
    public Result qiDatabaseGetFieldByTables(QiDatabase database) {
        QiDatabase qiDatabase = qiDatabaseMapper.selectById(database.getId());
        List<String> tables = database.getTables();
        List<String> collect = tables.stream().distinct().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)){
            return Result.succ(1, "连接成功！", new ArrayList<>());
        }
        List<Map<String,Object>> mapList=new ArrayList<>();
        try {
            QiDataSourceEnum anEnum = QiDataSourceEnum.getEnum(qiDatabase);
            DataBaseBo dataBaseBo = anEnum.getFunc().apply(anEnum, qiDatabase);
            JdbcConnectionManager jdbcConnectionManager = new JdbcConnectionManager();
            Connection connection = jdbcConnectionManager.getConnection(dataBaseBo);
            if(connection == null){
                return Result.fail("数据库连接失败，请查看连接信息或者数据服务状态！");
            }
            DatabaseMetaData metaData = connection.getMetaData();


            // 获取所有表
            for (String table : collect) {
                Map<String,Object>map=new HashMap<>();
                map.put("label",table);
                List<Map<String,String>> maps=new ArrayList<>();
                ResultSet columns = metaData.getColumns(null, null, table, "%");
                while (columns.next()) {
                    Map<String,String>fieldMap=new HashMap<>();
                    String columnName = columns.getString("COLUMN_NAME");
                    //String columnType = columns.getString("TYPE_NAME");
                    fieldMap.put("label",columnName);
                    fieldMap.put("value",table+"."+columnName);
                    maps.add(fieldMap);
                }
                map.put("options",maps);
                mapList.add(map);
            }

            jdbcConnectionManager.closeConnection(connection);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("数据库连接失败，请查看连接信息或者数据服务状态！");
        }
        return Result.succ(1, "连接成功！", mapList);
    }

    @Override
    public Result getQiDatabaseTableFieldList(QiDatabase database) {

        QiDatabase qiDatabase = qiDatabaseMapper.selectById(database.getId());
        List<String> tables = database.getTables();
        List<String> collect = tables.stream().distinct().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)){
            return Result.succ(1, "连接成功！", new ArrayList<>());
        }
        List<Map<String,Object>> mapList=new ArrayList<>();
        try {
            QiDataSourceEnum anEnum = QiDataSourceEnum.getEnum(qiDatabase);
            DataBaseBo dataBaseBo = anEnum.getFunc().apply(anEnum, qiDatabase);
            JdbcConnectionManager jdbcConnectionManager = new JdbcConnectionManager();
            Connection connection = jdbcConnectionManager.getConnection(dataBaseBo);
            if(connection == null){
                return Result.fail("数据库连接失败，请查看连接信息或者数据服务状态！");
            }
            DatabaseMetaData metaData = connection.getMetaData();


            // 获取所有表
            for (String table : collect) {
                Map<String,Object>map=new HashMap<>();
                map.put("label",table);
                map.put("value","");
                map.put("pLabel","");
                mapList.add(map);
                ResultSet columns = metaData.getColumns(null, null, table, "%");
                while (columns.next()) {
                    String columnName = columns.getString("COLUMN_NAME");

                    Map<String,Object>mapFiled=new HashMap<>();
                    mapFiled.put("label",columnName);
                    mapFiled.put("value",table+"."+columnName);
                    mapFiled.put("pLabel",table);
                    mapList.add(mapFiled);
                }

            }

            jdbcConnectionManager.closeConnection(connection);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("数据库连接失败，请查看连接信息或者数据服务状态！");
        }
        return Result.succ(1, "连接成功！", mapList);
    }
}
